package org.budo.netty.servlet.server.connector.netty;

import javax.servlet.DispatcherType;

import org.budo.netty.servlet.server.handler.BudoServletHandler;
import org.budo.netty.servlet.server.handler.servlet.BudoServletRequest;
import org.budo.netty.servlet.server.handler.servlet.BudoServletResponse;
import org.budo.netty.servlet.server.handler.servlet.DefaultBudoServletResponse;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;

/**
 * @author lmw
 */
public class NettyServletHandlerWrapper extends SimpleChannelInboundHandler<FullHttpRequest> {
    private BudoServletHandler servletHandler;

    public NettyServletHandlerWrapper(BudoServletHandler servletHandler) {
        this.servletHandler = servletHandler;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext handlerContext, FullHttpRequest nettyRequest) throws Exception {
        BudoServletRequest request = new NettyServletRequest(nettyRequest, this.servletHandler, handlerContext);
        BudoServletResponse response = new DefaultBudoServletResponse();

        this.servletHandler.handleRequest(request, response, DispatcherType.REQUEST);

        // 后处理执行，写到 HttpResponse
        NettyUtil.writeResponse(handlerContext, request, response);
    }

    /**
     * handle when exceptionCaught
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext handlerContext, Throwable e) throws Exception {
        BudoServletResponse response = new DefaultBudoServletResponse();

        // 异常处理
        this.servletHandler.getBudoServletServer().getExceptionHandler().handleException(response, e);

        // 后处理执行，写到 HttpResponse
        NettyUtil.writeResponse(handlerContext, null, response);
    }
}